package com.edu.lxshpc.handler;

import cn.hutool.json.JSONUtil;
import com.edu.lxshpc.utils.MyException;
import com.edu.lxshpc.utils.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zgh
 * @date 2023/11/20
 * 全局异常捕获，并处理
 */
@RestControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Result exceptionHandler(Exception e, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        if(e instanceof MyException){
            writer.println(JSONUtil.toJsonStr(Result.fail(e.getMessage())));
            writer.flush();
            return Result.fail(e.getMessage());
        }
        return Result.fail("未知错误");
    }
}
